package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemlate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@Service
public class UserInfoService {
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private UserApi userApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemlate aipFaceTemlate;

    /**
     * 添加用户信息
     *
     * @param userInfo
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 更新用户信息
     *
     * @param userInfo
     */
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    /**
     *  更新用户头像
     */
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemlate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if (/*!*/detect) {
            throw new RuntimeException();
        } else {
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    /**
     * 调用api查询用户详细信息
     *
     * @param userId
     * @return
     */
    public UserInfoVo findById(Long userId) {
//        获取用户详细信息
        UserInfo userInfo = userInfoApi.findById(userId);
//        创建页面所需要的值得对象
        UserInfoVo userInfoVo=new UserInfoVo();
        if(userInfo!=null) {
//        复制相同的参数
            BeanUtils.copyProperties(userInfo, userInfoVo);
            if(userInfo.getAge()!=null){
//        由于两个类的年龄类型不同需要单独设置
                userInfoVo.setAge(userInfo.getAge().toString());
            }
        }
        return userInfoVo;
    }
}
